package com.example.client_rpc.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {
    public static  final String RPC_MSG_SEND_QUEUE = "rpc_msg_send_queue";
    public static  final String RPC_MSG_RECV_QUEUE = "rpc_msg_recv_queue";//reply received
    public static  final String RPC_EXCHANGE_NAME = "rpc_exchange_name";

    @Bean
    Queue sendQueue(){
        //此queue专门用于向外界发消息

        return new Queue(RPC_MSG_SEND_QUEUE,true,false,false);
    }
    @Bean
    Queue recvQueue(){
        //此queue专门用于从外界收消息
        return new  Queue(RPC_MSG_RECV_QUEUE,true,false,false);

    }

    @Bean
    TopicExchange topicExchange(){
        return new TopicExchange(RPC_EXCHANGE_NAME,true,false);
    }

    @Bean
    Binding sendBind(){
        return BindingBuilder.bind(sendQueue()).to(topicExchange()).with(RPC_MSG_SEND_QUEUE);
    }

    @Bean
    Binding recvBind(){
        return BindingBuilder.bind(recvQueue()).to(topicExchange()).with(RPC_MSG_RECV_QUEUE);
    }

    @Bean
    RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setReplyAddress(RPC_MSG_RECV_QUEUE); //设置接受reply的地址（recv队列）
        rabbitTemplate.setReplyTimeout(6000);//wait reply timeout 6s
        return rabbitTemplate;
    }

    @Bean
    SimpleMessageListenerContainer replyContainer(ConnectionFactory connectionFactory){
        SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer(connectionFactory);
        simpleMessageListenerContainer.addQueueNames(RPC_MSG_RECV_QUEUE);//设置监听的队列 server
        //回送的消息放到这个queue里面，simple这个监听器告诉我（client）我好去取
        simpleMessageListenerContainer.setMessageListener(rabbitTemplate(connectionFactory));
        return simpleMessageListenerContainer;
    }

}
